package upload;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * 服务器  -- TCP
 */
public class UpServer {
    private ServerSocket serverSocket = null;

    public UpServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        while (true) {
            Socket socket = serverSocket.accept();
            Thread t = new Thread(() -> {
                processClient(socket);
            });
            t.start();
        }
    }
    public void processClient(Socket socket){
        System.out.printf("[ip: %s port: %d] 连接成功\n",socket.getInetAddress().toString(),socket.getPort());

        try(InputStream inputStream = socket.getInputStream()){
            try(OutputStream outputStream = socket.getOutputStream()){
                Scanner scanner = new Scanner(inputStream);
                String request = scanner.nextLine();
                process(request,outputStream);
                System.out.printf("[%s:%d]客户端断开连接\n",socket.getInetAddress().toString(),socket.getPort());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void process(String request,OutputStream outputStream) throws IOException {
        String fileName = "D:/picture/"+request+".png";
        InputStream inputStream = new FileInputStream(fileName);
 
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer,0,len);
        }
        outputStream.flush();
    }


    public static void main(String[] args) throws IOException {

        UpServer server = new UpServer(9090);
        server.start();
    }

}
